﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Chat.Common;


public class ChattingMsgPanel : MonoBehaviour
{
    public Transform chatContentRect;
    public InputField inputField;
    public Button sendMsgButton;
    public GameObject messageItemPrefab;

    private Queue<Message> messages = new Queue<Message>();

    private void Awake()
    {
        sendMsgButton.onClick.AddListener(SendMsg);
        Singleton<MessageManager>.GetInstance().OnMessageReceive += OnMessageReceive;
    }
    void Update()
    {
        if(messages.Count!=0)
            AddMessageItem(messages.Dequeue());
    }
    void SendMsg()
    {      
        ChattingPanel chattingPanel = GetComponentInParent<ChattingPanel>();
        Message msg = new Message()
        {
            ChatType = chattingPanel.ChatType,
            Sender = Singleton<Owner>.GetInstance() as ChatObject,
            Receiver = chattingPanel.ChatObject,
            Content = inputField.text
        };
        AddMessageItem(msg);
        Debug.Log(msg);
        Singleton<CommandSender>.GetInstance().SendChatMsg(msg);
    }
    void AddMessageItem(Message message)
    {
        GameObject go = Instantiate(messageItemPrefab);
        go.transform.SetParent(chatContentRect,false);
        go.GetComponent<MessageItem>().Message = message;
    }
    void OnMessageReceive(Message message)
    {
        messages.Enqueue(message);
    }
}
